<script setup>
import { nextTick, ref } from 'vue'
import { Plus, Minus } from '@element-plus/icons-vue'

import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import ElementSelect from './ElementSelect.vue'
import {
  AddRoutes,
  UpdateService,
  addImageService,
  deleteImageService
} from '@/api/line'

import alongScenicAreaSelect from './alongScenicAreaSelect.vue'
import { ElMessage } from 'element-plus'

const emit = defineEmits(['success'])
const visibleDrawer = ref(false)
const dialogVisible = ref(false)
const imgUrl = ref('')
const upload = ref()
const defaultModel = ref({
  routeMileage: '',
  routeName: '',
  routeStatus: '',
  routeTags: ['默认值'],
  spendTime: null,
  suitableTime: '',
  userId: null,
  alongScenicAreaVO: [],
  // scenicAreaStart: '',
  // scenicAreaEnd: '',
  alongElement: [],
  alongScenicArea: [],
  routeInfo: '',
  routeImages: [],
  routeImage: [],
  id: null,
  alongElementVO: [],
  routeElements: [],
  index: null
})
const fileList = ref([])
const formModel = ref({
  routeMileage: '',
  routeName: '',
  routeStatus: '',
  routeTags: [],
  spendTime: null,
  suitableTime: '',
  userId: null,
  alongScenicAreaVO: [],
  // scenicAreaStart: '',
  // scenicAreaEnd: '',
  alongElement: [],
  alongScenicArea: [],
  routeInfo: '',
  routeImages: [],
  routeImage: [],
  id: null,
  alongElementVO: [],
  routeElements: [],
  index: null
})
const editorRef = ref()
//添加规则
const rules = {
  routeName: [
    // { required: true, message: '请输入字符', trigger: 'blur' },
    {
      required: true,
      min: 3,
      max: 10,
      message: '线路名称为3-10的字符',
      trigger: 'blur'
    }
  ],
  //   routeElements: [
  //     { required: true, message: '请输入标签', trigger: 'change' }
  // ],
  //   alongScenicArea: [
  //     { required: true, message: '请输入沿途景区名称', trigger: 'change' },

  //   ],
  suitableTime: [
    // { required: true, message: '请输入适宜时间', trigger: 'blur' },
    {
      required: true,
      min: 1,
      max: 10,
      message: '适宜时间必须为1-10的数字',
      trigger: 'blur'
    }
  ],
  spendTime: [
    // { required: true, message: '请输入花费时间', trigger: 'blur' },
    {
      required: true,
      pattern: /^\d{1,10}$/,
      message: '花费时间必须为数字',
      trigger: 'blur'
    }
  ],
  scenicAreaImage: [
    { required: true, message: '请选择一张图片', trigger: 'blur' }
  ],
  routeMileage: [
    // { required: true, message: '请输入里程', trigger: 'blur' },
    {
      required: true,
      pattern: /^\d{1,10}$/,
      message: '里程必须为数字',
      trigger: 'blur'
    }
  ]
}
const months = [
  { value: '1', label: '一月' },
  { value: '2', label: '二月' },
  { value: '3', label: '三月' },
  { value: '4', label: '四月' },
  { value: '5', label: '五月' },
  { value: '6', label: '六月' },
  { value: '7', label: '七月' },
  { value: '8', label: '八月' },
  { value: '9', label: '九月' },
  { value: '10', label: '十月' },
  { value: '11', label: '十一月' },
  { value: '12', label: '十二月' }
]
//传递数据
const onPublish = async () => {
  // 打印 formModel 的值
  console.log('formModel:', formModel.value)

  // 检查必填字段
  const requiredFields = [
    'routeMileage',
    'routeName',
    'routeTags',
    'spendTime',
    'suitableTime',
    'routeInfo',
    'routeImages'
  ]

  const missingFields = requiredFields.filter(
    (field) => !formModel.value[field]
  )
  if (missingFields.length > 0) {
    ElMessage.error(`以下字段不能为空: ${missingFields.join(', ')}`)
    return
  }

  formModel.value
  if (
    Array.isArray(formModel.value.routeImages) &&
    formModel.value.routeImages.length === 0
  ) {
    ElMessage.error('请选择至少一张图片')
    return
  }

  const fd = new FormData()
  //额外添加图片的操作fd2
  const fd2 = new FormData()
  const textContent = formModel.value.routeInfo.replace(/<[^>]+>/g, '')

  fd.append('routeInfo', textContent)

  if (Array.isArray(formModel.value.routeImages)) {
    formModel.value.routeImages.forEach((image, index) => {
      fd.append(`routeImages[${index}]`, image)
    })
  }
  fd.append('routeMileage', formModel.value.routeMileage)
  fd.append('routeName', formModel.value.routeName)
  fd.append('routeTags', formModel.value.routeTags)
  fd.append('spendTime', formModel.value.spendTime)
  fd.append('suitableTime', formModel.value.suitableTime)

  fd.append('routeElements', formModel.value.routeElements)
  fd.append('alongScenicArea', formModel.value.alongScenicArea)
  const isEdit = formModel.value.id !== undefined && formModel.value.id !== null
  if (isEdit) {
    fd.append('id', formModel.value.id)
    fd2.append('id', formModel.value.id)
    if (Array.isArray(formModel.value.routeImages)) {
      formModel.value.routeImages.forEach((routeImage) => {
        fd2.append('routeImage', routeImage)
      })
    }
    //编辑操作
    console.log('alongScenicArea', formModel.value.alongScenicArea)
    console.log('routeElements', formModel.value.routeElements)
  }
  console.log('Form data being sent:', Array.from(fd2.entries()))
  console.log('Form data being sent:', Array.from(fd.entries())) // 打印FormData内容
  try {
    let res
    let res1
    if (isEdit) {
      console.log('Updating service with data:', fd)
      res = await UpdateService(fd)
      res1 = await addImageService(fd2)
    } else {
      console.log('Adding route with data:', fd)

      res = await AddRoutes(fd)
    }
    console.log('Operation response:', res)
    if (res && res.code === 401 && res1 && res1.code === 200) {
      ElMessage.error(res.message || '操作失败')
      ElMessage.error(res1.message || '操作失败')
    } else {
      ElMessage.success(isEdit ? '编辑成功' : '添加成功')
      // 传递给父组件实现刷新

      emit('success')
      visibleDrawer.value = false
    }
  } catch (error) {
    console.error('Form submission error:', error)
    if (error.response) {
      console.error('API response:', error.response)
    }
    ElMessage.error('表单提交失败，请检查输入')
  }
}
const open = async (row) => {
  visibleDrawer.value = true
  console.log('row', row)
  if (row && row.id) {
    console.log('formModel.value1', formModel.value)

    console.log('row', row)
    formModel.value = { ...formModel, ...row }
    console.log('formModel.value2', formModel.value)

    // formModel.value = { row }
    // if (!Array.isArray(formModel.value.routeTags)) {
    //   formModel.value.routeTags = []
    // }
    imgUrl.value = ''
    formModel.value.routeImages = []
    fileList.value = []
    formModel.value.routeElements = row.alongElementVO.map((item) => item.id)
    // 遍历获取id
    formModel.value.alongScenicArea = row.alongScenicAreaVO.map(
      (item) => item.id
    )
    console.log(
      'formModel.value.alongScenicArea',
      formModel.value.alongScenicArea
    )
    console.log('routeElements', formModel.value.routeElements)
    // formModel.value.routeId = row.routeId
    formModel.value.routeName = row.routeName
    //imgUrl.value = row.routeImage
    const imagesWithUid = row.routeImage.map((imgUrl, index) => ({
      url: imgUrl,
      uid: -index - 1, // 使用负数确保唯一性
      name: `image-${index}.jpg`
    }))
    fileList.value = imagesWithUid
    console.log('fileList.value', fileList.value)
    // 处理图片回显
    // if (Array.isArray(row.routeImages)) {
    //   row.routeImages.forEach((image) => {
    //     formModel.value.routeImages.push(image)
    //     fileList.value.push({
    //       url: image.url,
    //       name: image.name,
    //       raw: image
    //     })
    //   })
    // }
  } else {
    formModel.value = { ...defaultModel }
    formModel.value.routeTags = []
    formModel.value.routeImages = []
    formModel.value.alongScenicArea = []
    formModel.value.routeElements = []
    imgUrl.value = ''
    nextTick(() => {
      if (editorRef.value) {
        editorRef.value.setHTML('')
      }
    })
  }
  console.log('fileList after open:', fileList.value)

  console.log('formModel after open:', formModel.value)
}
// 添加路线标签
const addTag = () => {
  formModel.value.routeTags.push('')
}
//减少标签
const minusTag = () => {
  if (formModel.value.routeTags.length > 0) {
    formModel.value.routeTags.pop()
  }
}

//处理图片
const handlePictureCardPreview = (file) => {
  console.log(file)
}
//删除
// const removeImage = async (file, index) => {
//   if (!Array.isArray(fileList.value)) {
//     ElMessage.error('文件列表数据格式错误，请刷新页面后重试')
//     return
//   }
//   // 获取当前文件列表和图片列表
//   // 对应参数
//   console.log(index, formModel.value.id)
//   const data = {
//     id: formModel.value.id,
//     imageIndex: index
//   }
//   const res = await deleteImageService(data)
//   console.log('res', res)
//   if (res && res.data.code === 200) {
//     ElMessage.success('删除成功')
//     // 从 formModel.value.routeImages 中移除已删除的图片
//     formModel.value.routeImage = formModel.value.routeImage.splice(index, 1)
//   } else {
//     ElMessage.error('删除失败')
//   }
// }

const handleRemove = async (file) => {
  if (!Array.isArray(fileList.value)) {
    ElMessage.error('文件列表数据格式错误，请刷新页面后重试')
    return
  }
  //索引
  const index = fileList.value.findIndex((item) => item.uid === file.uid)
  console.log('index', index)
  if (index === -1) {
    ElMessage.success('文件未找到')
    // console.log('index', index)
    return
  }
  //获取当前文件列表和图片列表对对应的参数
  console.log('imageIndex, id', index, formModel.value.id)
  const data = {
    id: formModel.value.id,
    imageIndex: index
  }
  try {
    const res = await deleteImageService(data)
    console.log('res', res)
    if (res && res.data.code === 200) {
      ElMessage.success('删除成功')
      // 从 formModel.value.routeImages 中移除已删除的图片
      formModel.value.routeImage = formModel.value.routeImage.splice(index, 1)
    } else {
      ElMessage.error('删除失败')
    }
  } catch (error) {
    console.error('Error deleting image:', error)
  }
}

const onSelectFile = (file) => {
  // console.log(URL.createObjectURL(file.raw))
  console.log(file)

  if (file) {
    if (!Array.isArray(formModel.value.routeImages)) {
      formModel.value.routeImages = []
    }
    formModel.value.routeImages.push(file.raw) // 存储文件对象
    fileList.value = formModel.value.routeImages.map((image) => ({
      url: URL.createObjectURL(image),
      name: image.name,
      raw: image
    }))

    console.log(fileList.value)
  }
  console.log('File selected:', file.raw) // 打印文件信息
}

// 处理下拉问题

defineExpose({ open })
</script>
<template>
  <el-drawer
    v-model="visibleDrawer"
    :title="formModel.id ? '编辑路线' : '添加路线'"
    direction="rtl"
    size="50%"
  >
    <!-- 发表表单 -->
    <el-form
      :model="formModel"
      :rules="rules"
      ref="formRef"
      label-width="100px"
    >
      <el-form-item label="路线名称" prop="routeName">
        <el-input
          v-model="formModel.routeName"
          placeholder="请输入路线名称"
        ></el-input>
      </el-form-item>

      <el-form-item
        label="标签"
        prop="routeElements"
        style="text-align: center"
      >
        <element-select v-model="formModel.routeElements"></element-select>
      </el-form-item>

      <el-form-item label="沿途景区" prop="alongScenicArea">
        <alongScenicAreaSelect
          v-model="formModel.alongScenicArea"
        ></alongScenicAreaSelect>
      </el-form-item>

      <el-form-item label="Tags" prop="routeTags">
        <el-row :gutter="25">
          <el-col
            :span="8"
            v-for="(tag, index) in formModel.routeTags"
            :key="index"
          >
            <el-input
              v-model="formModel.routeTags[index]"
              placeholder="添加标签"
              style="width: 150px; margin-right: 15px"
            ></el-input>
          </el-col>
        </el-row>
        <el-button
          type="primary"
          @click="addTag"
          :icon="Plus"
          style="margin-left: 25px"
        ></el-button>
        <el-button
          type="primary"
          @click="minusTag"
          :icon="Minus"
          style="margin-left: 25px"
        ></el-button>
      </el-form-item>

      <el-form
        :model="formModel"
        :rules="rules"
        inline
        style="margin-left: 15px"
      >
        <el-form-item
          label="适宜时间(月)"
          style="padding-right: 5px"
          prop="suitableTime"
        >
          <!-- <el-date-picker type="month" placeholder="选择日期"  v-model="formModel.suitableTime" style="width: 220%;" format="MM" ></el-date-picker> -->
          <el-select
            v-model="formModel.suitableTime"
            placeholder="选择日期"
            style="width: 220px"
          >
            <el-option
              v-for="(month, index) in months"
              :key="index"
              :label="month.label"
              :value="month.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="花费时间时间(天)" prop="spendTime">
          <el-input
            placeholder="请输入预计花费时间"
            clearable
            style="width: 240px"
            v-model="formModel.spendTime"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-form-item label="景区图片" prop="scenicAreaImage">
        <!-- <el-row :gutter="25">
          <el-col
            :span="10"
            v-for="(image, index) in formModel.routeImage"
            :key="index"
          >
            <img
              :src="image"
              alt="景区图片"
              style="width: 170px; height: auto; margin-right: 15px"
              @click="removeImage({raw:image},index)"
              cursor: pointer
            />
          </el-col>
        </el-row> -->

        <el-upload
          style="margin-left: 20px"
          class="avatar-uploader"
          :show-file-list="true"
          v-model:file-list="fileList"
          list-type="picture-card"
          :auto-upload="false"
          :on-change="onSelectFile"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          action="https://jsonplaceholder.typicode.com/posts/"
          ref="upload"
          ><i class="el-icon-plus"></i>
        </el-upload>
        <el-dialog v-model:visible="dialogVisible"> </el-dialog>
      </el-form-item>

      <el-form-item label="里程(km)" prop="routeMileage">
        <el-input
          v-model="formModel.routeMileage"
          placeholder="请输入距离"
        ></el-input>
      </el-form-item>

      <el-form-item label="景区介绍" prop="routeInfo">
        <div class="editor">
          <quill-editor
            theme="snow"
            v-model:content="formModel.routeInfo"
            contentType="html"
            ref="editorRef"
          >
          </quill-editor>
        </div>
      </el-form-item>
      <el-form-item>
        <el-button @click="onPublish" type="primary">发布</el-button>
        <el-button @click="visibleDrawer = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }
    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }
    .el-upload:hover {
      border-color: var(--el-color-primary);
    }
    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}

.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
.el-icon--upload {
  margin-left: 50px;
}
.mapInput {
  // margin-right: 10px;
  display: inline-block;
}
</style>
